"use strict";
//前后端HTTP协议交互
//因为request 回调函数参数[err, res, body]问题无法直接转换成Promise模式
const mvc = require('cosjs.mvc');
const request = mvc.library.require('request');
//向游戏服发送数据
exports.select = function(branch,sid,avg){
    return Promise.resolve().then(()=>{
        let b = typeof branch === 'object' ? branch._id : branch;
        let p = mvc.config.get("local.port")||8080;
        let r = mvc.config.get("spirit.route")||'spirit';
        let api = ['',b,r,'select'].join('/');
        let uri = ['http://127.0.0.1',p].join(':')
        let url = [uri,api].join('');
        let data = {"ts":1,"sid":sid,"avg":avg||0};
        return request.post(url,data,true);
    }).then(ret=>mvc.library('promise/callback',ret))
}

exports.request = function(branch,sid,api,data){
    return exports.select(branch,sid).then(ret=>{
        if(!ret){
            console.log("branch and sid  ",branch,sid);
            return Promise.reject("server empty")
        }
        let url = 'http://'+ret['ip']+':' + ret['local'] + '/s'+sid+ api;
        let secret = mvc.config.get("secret");
        mvc.library("sign/create",data,secret);
        return request.post(url,data,true).then(ret=>mvc.library('promise/callback',ret))
    })
}

/**
 * @name notify * 回调,游戏发货
 */
//rmb,orderid
exports.notify = function(branch,sid,data){
    let api = '/order/notify';
    return exports.request(branch,sid,api,data);
}
